<template>
  <div class="user-edit-container">
    <div class="edit-header">
      <h1>编辑用户</h1>
      <p>修改用户信息</p>
    </div>

    <div class="edit-card" v-if="user">
      <div class="user-header">
        <div class="user-avatar">
          {{ user.username.charAt(0).toUpperCase() }}
        </div>
        <div class="user-details">
          <h2>{{ user.username }}</h2>
          <p class="user-id">用户ID: {{ user.userId }}</p>
        </div>
      </div>

      <form @submit.prevent="handleUpdate" class="edit-form">
        <div class="form-section">
          <h3>基本信息</h3>
          <div class="form-grid">
            <div class="form-group">
              <label>用户名</label>
              <input
                type="text"
                v-model="form.username"
                disabled
                class="disabled-input"
              />
              <div class="field-note">用户名不可修改</div>
            </div>

            <div class="form-group">
              <label>邮箱 <span class="required">*</span></label>
              <input
                type="email"
                v-model="form.email"
                @blur="validateField('email')"
                :class="{ 'error': errors.email }"
                placeholder="请输入邮箱"
              />
              <div v-if="errors.email" class="error-message">{{ errors.email }}</div>
            </div>

            <div class="form-group">
              <label>真实姓名</label>
              <input
                type="text"
                v-model="form.realName"
                placeholder="请输入真实姓名"
              />
            </div>

            <div class="form-group">
              <label>手机号</label>
              <input
                type="tel"
                v-model="form.phone"
                @blur="validateField('phone')"
                :class="{ 'error': errors.phone }"
                placeholder="请输入手机号"
              />
              <div v-if="errors.phone" class="error-message">{{ errors.phone }}</div>
            </div>
          </div>
        </div>

        <div class="form-section">
          <h3>角色管理</h3>
          <div class="form-grid">
            <div class="form-group">
              <label>当前角色</label>
              <input type="text" :value="rolesDisplay" disabled class="disabled-input" />
              <div class="field-note">管理员可为普通用户配置角色</div>
            </div>

            <div class="form-group">
              <label>分配角色（单选）</label>
              <div class="role-checkboxes">
                <label class="checkbox-label">
                  <input type="radio" v-model="selectedRoleId" :value="1" />
                  <span class="checkmark"></span>
                  管理员 / admin（ID:1）
                </label>
                <label class="checkbox-label">
                  <input type="radio" v-model="selectedRoleId" :value="2" />
                  <span class="checkmark"></span>
                  普通用户 / user（ID:2）
                </label>
              </div>
              <div class="field-note">如需更多角色，请在后端角色表中维护</div>
            </div>
          </div>
        </div>

        

        <div class="form-section" v-if="user.createdAt || user.updatedAt">
          <h3>系统信息</h3>
          <div class="system-info">
            <div class="info-item" v-if="user.createdAt">
              <label>创建时间:</label>
              <span>{{ formatDateTime(user.createdAt) }}</span>
            </div>
            <div class="info-item" v-if="user.updatedAt">
              <label>最后更新:</label>
              <span>{{ formatDateTime(user.updatedAt) }}</span>
            </div>
          </div>
        </div>

        <div class="form-actions">
          <button
            type="button"
            class="btn-cancel"
            @click="goBack"
          >
            取消
          </button>
          <button
            type="submit"
            class="btn-save"
            :disabled="!isFormValid || isLoading"
          >
            <span v-if="isLoading" class="btn-spinner"></span>
            {{ isLoading ? '保存中...' : '保存更改' }}
          </button>
        </div>
      </form>
    </div>

    <div v-else class="loading-state">
      <div class="loading-spinner"></div>
      <p>加载用户信息中...</p>
    </div>

    <!-- 成功提示 -->
    <div v-if="showSuccess" class="success-overlay" @click="showSuccess = false">
      <div class="success-card" @click.stop>
        <div class="success-icon">✅</div>
        <h3>保存成功！</h3>
        <p>用户信息已更新</p>
        <button class="btn-confirm" @click="showSuccess = false">确定</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import type { User } from '@/api/user'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const user = ref<User | null>(null)
const isLoading = ref(false)
const showSuccess = ref(false)
const selectedRoleId = ref<number | null>(null)

const form = reactive({
  username: '',
  email: '',
  realName: '',
  phone: ''
})

const errors = reactive({
  email: '',
  phone: ''
})

const isFormValid = computed(() => {
  return form.email && !errors.email && !errors.phone
})

const rolesDisplay = computed(() => {
  if (!user.value?.roles || user.value.roles.length === 0) return '-'
  return user.value.roles.join(', ')
})

const validateField = (field: string) => {
  const value = (form as any)[field]
  
  switch (field) {
    case 'email':
      if (!value) {
        errors.email = '请输入邮箱'
      } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
        errors.email = '请输入有效的邮箱地址'
      } else {
        errors.email = ''
      }
      break
      
    case 'phone':
      if (value && !/^1[3-9]\d{9}$/.test(value)) {
        errors.phone = '请输入有效的手机号'
      } else {
        errors.phone = ''
      }
      break
  }
}

const formatDateTime = (dateString?: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

const loadUser = async () => {
  const userId = parseInt(route.params.id as string)
  if (!userId) {
    alert('用户ID无效')
    router.back()
    return
  }

  try {
    const response = await userStore.fetchAllUsers()
    if (response.operateResult === 'SUCCESS' && response.data) {
      const foundUser = response.data.find((u: User) => u.userId === userId)
      if (foundUser) {
        user.value = foundUser
        Object.assign(form, {
          username: foundUser.username,
          email: foundUser.email,
          realName: foundUser.realName || '',
          phone: foundUser.phone || ''
        })

        // 获取该用户的角色（名称）并预设选中角色ID（基于常见映射 1->admin, 2->user）
        if (foundUser.username) {
          const roleResp = await userStore.fetchUserRoles(foundUser.username)
          if (roleResp.operateResult === 'SUCCESS') {
            user.value.roles = roleResp.roles
            const roleToId: Record<string, number> = { admin: 1, user: 2 }
            const ids = (roleResp.roles || []).map(r => roleToId[r]).filter(Boolean)
            selectedRoleId.value = ids.length > 0 ? ids[0] : 2
          }
        }
      } else {
        alert('用户不存在')
        router.back()
      }
    }
  } catch (error) {
    alert('加载用户信息失败')
    router.back()
  }
}

const handleUpdate = async () => {
  if (!user.value) return
  
  validateField('email')
  validateField('mobile')
  
  if (!isFormValid.value) return
  
  isLoading.value = true
  
  try {
    const result = await userStore.updateUserInfo(user.value.userId!, form)
    if (result.operateResult !== 'SUCCESS') {
      alert(result.errorMsg || '更新失败')
      return
    }

    // 先根据当前用户的用户名更新角色
    const roleIdsToSend = selectedRoleId.value != null ? [selectedRoleId.value] : []
    const roleUpdate = await userStore.updateUserRoles(user.value.username, roleIdsToSend)
    if (roleUpdate.operateResult !== 'SUCCESS') {
      alert(roleUpdate.errorMsg || '更新角色失败')
      return
    }

    showSuccess.value = true
    setTimeout(() => {
      showSuccess.value = false
      router.push('/admin/users')
    }, 1500)
  } catch (error) {
    alert('更新失败，请稍后重试')
  } finally {
    isLoading.value = false
  }
}

const goBack = () => {
  router.back()
}

onMounted(() => {
  loadUser()
})
</script>

<style scoped>
.user-edit-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 40px 20px;
}

.edit-header {
  text-align: center;
  margin-bottom: 40px;
}

.edit-header h1 {
  font-size: 32px;
  color: #1e293b;
  margin-bottom: 8px;
  font-weight: 600;
}

.edit-header p {
  color: #64748b;
  font-size: 16px;
}

.edit-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  padding: 40px;
  border: 1px solid #e2e8f0;
}

.user-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 40px;
  padding-bottom: 30px;
  border-bottom: 1px solid #f1f5f9;
}

.user-avatar {
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  font-weight: bold;
}

.user-details h2 {
  font-size: 24px;
  color: #1e293b;
  margin-bottom: 4px;
}

.user-id {
  color: #64748b;
  font-size: 14px;
}

.edit-form {
  display: flex;
  flex-direction: column;
  gap: 32px;
}

.form-section {
  border: 1px solid #f1f5f9;
  border-radius: 12px;
  padding: 24px;
  background: #fafbfc;
}

.form-section h3 {
  font-size: 18px;
  color: #1e293b;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e2e8f0;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  color: #374151;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
}

.required {
  color: #ef4444;
}

.form-group input {
  padding: 12px 16px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.2s;
  background: white;
}

.form-group input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-group input.error {
  border-color: #ef4444;
}

.form-group input.disabled-input {
  background: #f9fafb;
  color: #6b7280;
  cursor: not-allowed;
}

.field-note {
  font-size: 12px;
  color: #6b7280;
  margin-top: 6px;
}

.error-message {
  color: #ef4444;
  font-size: 12px;
  margin-top: 6px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  font-weight: 500;
}

.role-checkboxes {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.checkbox-label input {
  display: none;
}

.checkmark {
  width: 20px;
  height: 20px;
  border: 2px solid #d1d5db;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.checkbox-label input:checked + .checkmark {
  background: #3b82f6;
  border-color: #3b82f6;
}

.checkbox-label input:checked + .checkmark::after {
  content: '✓';
  color: white;
  font-size: 14px;
  font-weight: bold;
}

.system-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.info-item label {
  font-weight: 500;
  color: #374151;
  font-size: 14px;
}

.info-item span {
  color: #64748b;
  font-size: 14px;
}

.form-actions {
  display: flex;
  gap: 16px;
  justify-content: flex-end;
  margin-top: 20px;
  padding-top: 30px;
  border-top: 1px solid #e5e7eb;
}

.btn-cancel {
  background: #6b7280;
  color: white;
  border: none;
  padding: 12px 28px;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.2s;
}

.btn-cancel:hover {
  background: #4b5563;
}

.btn-save {
  background: #3b82f6;
  color: white;
  border: none;
  padding: 12px 28px;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: background-color 0.2s;
}

.btn-save:hover:not(:disabled) {
  background: #2563eb;
}

.btn-save:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f1f5f9;
  border-top: 4px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

.loading-state p {
  color: #64748b;
}

/* 成功提示 */
.success-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.success-card {
  background: white;
  padding: 40px;
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
  text-align: center;
  max-width: 400px;
  width: 90%;
}

.success-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.success-card h3 {
  color: #1e293b;
  font-size: 24px;
  margin-bottom: 12px;
}

.success-card p {
  color: #64748b;
  margin-bottom: 24px;
}

.btn-confirm {
  background: #3b82f6;
  color: white;
  border: none;
  padding: 10px 24px;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
}

.btn-confirm:hover {
  background: #2563eb;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-edit-container {
    padding: 20px 16px;
  }
  
  .edit-card {
    padding: 24px 16px;
  }
  
  .form-grid {
    grid-template-columns: 1fr;
  }
  
  .user-header {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .info-item span {
    text-align: left;
  }
}
</style>